package io.renren.sf.controller;

import com.alibaba.fastjson.JSONObject;
import com.hz.common.utils.ResponseData;
import com.hz.common.utils.ResponsePage;
import com.hz.utils.FixedInformationName;
import io.renren.common.utils.Download;
import io.renren.common.utils.MD5;
import io.renren.common.utils.R;
import io.renren.sf.entity.*;
import io.renren.sf.feign.OssFeign;
import io.renren.sf.service.*;
import io.renren.sf.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author cyl_txw
 * @email cyl_txw@gmail.com
 * @date 2023-05-09 15:02:11
 */
@RestController
@RequestMapping("sf/selectedCopyingExamples")
@Api(tags = "精临例字管理")
public class SelectedCopyingExamplesController {

    @Autowired
    private HzFixedInformationDicService fixedInformationDicService;

    @Autowired
    private HzSelectedCopyingExamplesService copyingExamplesService;

    @Autowired
    private HzSelectedCopyingExamplesCharacterService copyingExamplesCharacterService;

    @Autowired
    private SelectedCopyingExamplesSinglepageService selectedCopyingExamplesSinglepageService;

    @Autowired
    private OssFeign ossFeign;


    /**
     * 精临例字字删除
     */
    @ApiOperation("精临例字字列表删除")
    @PostMapping("/examplesChr/delete")
    public ResponseData examplesChrDelete(@RequestBody Long[] ids){
        copyingExamplesCharacterService.removeByIds(Arrays.asList(ids));
        return ResponseData.success("删除成功");
    }

    /**
     * 精临例字字修改
     */
    @ApiOperation("精临例字字修改")
    @PostMapping("/examplesChr/update")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "精临例字字id", paramType = "query", dataType = "Long", required = true),
            @ApiImplicitParam(name = "excharacter1", value = "精临例字字原图src", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "excharacter2", value = "精临例字字单钩src", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "excharacter3", value = "精临例字字双钩src", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "excharacter4", value = "精临例字字描红src", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "excharacter5", value = "精临例字字动态src", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "corder", value = "顺序", paramType = "query", dataType = "int", required = true)
    })
    public ResponseData examplesChrUpdate(@RequestParam("id") Long id,
                                          @RequestParam("excharacter1") String excharacter1,
                                          @RequestParam("excharacter2") String excharacter2,
                                          @RequestParam("excharacter3") String excharacter3,
                                          @RequestParam("excharacter4") String excharacter4,
                                          @RequestParam("excharacter5") String excharacter5,
                                          @RequestParam("corder") Integer corder){
        HzSelectedCopyingExamplesCharacterEntity seCoExamCharacter = new HzSelectedCopyingExamplesCharacterEntity(id,
                excharacter1,
                excharacter2,
                excharacter3,
                excharacter4,
                excharacter5,
                corder);
        copyingExamplesCharacterService.updateById(seCoExamCharacter);
        return ResponseData.success("修改成功");
    }

    /**
     * 精临例字字新增
     */
    @ApiOperation("精临例字字保存")
    @PostMapping("/examplesChr/save")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "excharacter1", value = "精临例字字原图src", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "excharacter2", value = "精临例字字单钩src", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "excharacter3", value = "精临例字字双钩src", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "excharacter4", value = "精临例字字描红src", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "excharacter5", value = "精临例字字动态src", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "sid", value = "精临例字单页id", paramType = "query", dataType = "Long", required = true),
            @ApiImplicitParam(name = "corder", value = "顺序", paramType = "query", dataType = "int", required = true)
    })
    public ResponseData examplesChrSave(@RequestParam("excharacter1") String excharacter1,
                                        @RequestParam("excharacter2") String excharacter2,
                                        @RequestParam("excharacter3") String excharacter3,
                                        @RequestParam("excharacter4") String excharacter4,
                                        @RequestParam("excharacter5") String excharacter5,
                                        @RequestParam("sid") Long sid,
                                        @RequestParam("corder") int corder){
        HzSelectedCopyingExamplesCharacterEntity seCoExamCharacter = new HzSelectedCopyingExamplesCharacterEntity(excharacter1,
                excharacter2,
                excharacter3,
                excharacter4,
                excharacter5,
                sid,
                corder);
        copyingExamplesCharacterService.save(seCoExamCharacter);
        return ResponseData.success("保存成功");
    }

    /**
     * 精临例字结构种类获取
     */
    @ApiOperation("精临例字结构种类获取")
    @GetMapping("/examplesType/get")
    public ResponseData<CopyingExamplesStructureTypeVo> examplesTypeGet() {
        // 查询所有的精临例字结构名称
        List<HzFixedInformationDicEntity> fixedInformationDicList = fixedInformationDicService.queryByName(FixedInformationName.SE_CO_EXAMPLES_STRUCTURE);
        // 映射成vo List
        List<CopyingExamplesStructureTypeVo> coExamStrucTypeVoList = fixedInformationDicList.stream()
                .map(fixedInformationDic -> new CopyingExamplesStructureTypeVo(
                        fixedInformationDic.getId(),
                        fixedInformationDic.getFixedInformationContent()
                ))
                .collect(Collectors.toList());
        return ResponseData.success(coExamStrucTypeVoList);
    }

    /**
     * 碑帖修改
     */
    @ApiOperation("精临例字单页修改")
    @PostMapping("/examplessinglepage/update")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "碑帖单页id", paramType = "query", dataType = "Long", required = true),
            @ApiImplicitParam(name = "copyingExamplesSinglepageName", value = "精临例字单页名称", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "copyingExamplesSinglepage", value = "精临例字单页src", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "sid", value = "精临例字id", paramType = "query", dataType = "Long", required = true),
            @ApiImplicitParam(name = "sorder", value = "顺序", paramType = "query", dataType = "Integer", required = true)
    })
    public ResponseData examplessinglepageUpdate(@RequestParam("id") long id,
                                                         @RequestParam("copyingExamplesSinglepageName") String copyingExamplesSinglepageName,
                                                         @RequestParam("copyingExamplesSinglepage") String copyingExamplesSinglepage,
                                                         @RequestParam("sid") long sid,
                                                         @RequestParam("sorder") int sorder){
        SelectedCopyingExamplesSinglepageEntity selectedCopyingExamplesSinglepage = new SelectedCopyingExamplesSinglepageEntity(
                id,
                copyingExamplesSinglepageName,
                copyingExamplesSinglepage,
                sid,
                sorder
        );
        selectedCopyingExamplesSinglepageService.updateById(selectedCopyingExamplesSinglepage);
        return ResponseData.success("修改成功");
    }

    /**
     * 碑帖保存
     */
    @ApiOperation("精临例字单页保存")
    @PostMapping("/examplessinglepage/save")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "copyingExamplesSinglepageName", value = "精临例字单页名称", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "copyingExamplesSinglepage", value = "精临例字单页src", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "sid", value = "精临例字id", paramType = "query", dataType = "Long", required = true),
            @ApiImplicitParam(name = "sorder", value = "顺序", paramType = "query", dataType = "Integer", required = true)
    })
    public ResponseData examplessinglepageSave(@RequestParam("copyingExamplesSinglepageName") String copyingExamplesSinglepageName,
                                                       @RequestParam("copyingExamplesSinglepage") String copyingExamplesSinglepage,
                                                       @RequestParam("sid") long sid,
                                                       @RequestParam("sorder") int sorder) {
        SelectedCopyingExamplesSinglepageEntity selectedCopyingExamplesSinglepage = new SelectedCopyingExamplesSinglepageEntity(
                copyingExamplesSinglepageName,
                copyingExamplesSinglepage,
                sid,
                sorder
        );
        selectedCopyingExamplesSinglepageService.save(selectedCopyingExamplesSinglepage);
        return ResponseData.success("保存成功");
    }

    /**
     * 精临例字单页列表删除
     */
    @ApiOperation("精临例字单页列表删除")
    @PostMapping("/examplessinglepage/delete")
    public ResponseData examplessinglepageDelete(@RequestBody Long[] ids){
        selectedCopyingExamplesSinglepageService.removeByIds(Arrays.asList(ids));
        return ResponseData.success("删除成功");
    }


    /**
     * 精临例字分页查询
     */
    @ApiOperation("精临例字分页列表")
    @PostMapping("/examples/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "curPage", value = "当前页数", paramType = "query", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", paramType = "query", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "condition", value = "模糊查询条件", paramType = "query", dataType = "String", required = false),
            @ApiImplicitParam(name = "structureType", value = "结构种类", paramType = "query", dataType = "String", required = false)
    })
    public ResponseData<ResponsePage<List<SelectedCopyingExamplesCharacterVo>>> examplesPage(@RequestParam("curPage") Integer curPage,
                                                                                             @RequestParam("pageSize") Integer pageSize,
                                                                                             @RequestParam(value = "condition", required = false) String condition,
                                                                                             @RequestParam(value = "structureType", required = false) String structureType) {

        List<SelectedCopyingExamplesCharacterVo> copyingSteleCalligraphyList = copyingExamplesService.queryExamples(curPage, pageSize, structureType, condition);

        ResponsePage<List<SelectedCopyingExamplesCharacterVo>> page = new ResponsePage<>(
                copyingSteleCalligraphyList,
                copyingExamplesService.queryExamplesNum(structureType, condition),
                pageSize
        );
        return ResponseData.success(page);
    }

    /**
     * 精临例字列表删除
     */
    @ApiOperation("精临例字列表删除")
    @PostMapping("/examples/delete")
    public ResponseData examplesDelete(@RequestBody Long[] ids){
        copyingExamplesService.removeByIds(Arrays.asList(ids));
        return ResponseData.success("删除成功");
    }

    /**
     * 精临例字保存
     */
    @ApiOperation("精临例字保存")
    @PostMapping("/examples/save")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "copyingExamplesSrc", value = "精临例字src", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "copyingExamplesName", value = "精临例字名称", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "sid", value = "结构种类id", paramType = "query", dataType = "Long", required = true),
            @ApiImplicitParam(name = "sorder", value = "顺序", paramType = "query", dataType = "Integer", required = true)
    })
    public ResponseData examplesSave(@RequestParam("copyingExamplesSrc") String copyingExamplesSrc,
                                     @RequestParam("copyingExamplesName") String copyingExamplesName,
                                     @RequestParam("sid") Long sid,
                                     @RequestParam("sorder") Integer sorder) {
        HzFixedInformationDicEntity fixedInformationDic = fixedInformationDicService.getById(sid);
        if(fixedInformationDic == null) return ResponseData.success("保存失败，请重试！",false);
        // 制作缩略图
        String copyingExamplesThumbnailSrc = getThumbnailUrl(copyingExamplesSrc);
        if (copyingExamplesThumbnailSrc.equals(""))    return ResponseData.error(500, "保存失败，缩略图制作失败！");

        HzSelectedCopyingExamplesEntity hzSelectedCopyingExamples = new HzSelectedCopyingExamplesEntity(copyingExamplesSrc,
                copyingExamplesThumbnailSrc,
                copyingExamplesName,
                fixedInformationDic.getFixedInformationContent(),
                sorder,
                new Date(),
                sid);
        copyingExamplesService.save(hzSelectedCopyingExamples);
        return ResponseData.success("保存成功");
    }

    /**
     * 精临例字修改
     */
    @ApiOperation("精临例字修改")
    @PostMapping("/examples/update")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "精临例字id", paramType = "query", dataType = "Long", required = true),
            @ApiImplicitParam(name = "copyingExamplesSrc", value = "精临例字src", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "copyingExamplesName", value = "精临例字名称", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "sid", value = "结构种类id", paramType = "query", dataType = "Long", required = true),
            @ApiImplicitParam(name = "sorder", value = "顺序", paramType = "query", dataType = "int", required = true)
    })
    public ResponseData examplesUpdate(@RequestParam("id") Long id,
                                       @RequestParam("copyingExamplesSrc") String copyingExamplesSrc,
                                       @RequestParam("copyingExamplesName") String copyingExamplesName,
                                       @RequestParam("sid") long sid,
                                       @RequestParam("sorder") int sorder) {
        HzFixedInformationDicEntity fixedInformationDic = fixedInformationDicService.getById(sid);
        if(fixedInformationDic == null) return ResponseData.success("修改失败，请重试！",false);
        // 制作缩略图
        String copyingExamplesThumbnailSrc = getThumbnailUrl(copyingExamplesSrc);
        if (copyingExamplesThumbnailSrc.equals(""))    return ResponseData.error(500, "修改失败，缩略图制作失败！");

        HzSelectedCopyingExamplesEntity hzSelectedCopyingExamples = new HzSelectedCopyingExamplesEntity(id,
                copyingExamplesSrc,
                copyingExamplesThumbnailSrc,
                copyingExamplesName,
                fixedInformationDic.getFixedInformationContent(),
                sorder,
                new Date(),
                sid);
        copyingExamplesService.updateById(hzSelectedCopyingExamples);
        return ResponseData.success("修改成功");
    }

    /**
     * 创建缩略图
     * 下载原图-制作缩略图-上传-获取缩略图地址
     * @param picUrl
     * @return
     */
    private String getThumbnailUrl(String picUrl){
        String suffix = picUrl.substring(picUrl.lastIndexOf("."));
        String md5 = MD5.encrypt(picUrl);
        String savePath = "/tmp/copyingExamples/";
        // 下载原图
        Download.download(picUrl, md5 + suffix, savePath);
        // 制作缩略图
        String originalDrawingUrl = savePath + md5 + suffix;
        String thumbnailUrl = savePath + md5 + "_thumbnail" + suffix;
        File originalDrawing = new File(originalDrawingUrl);
        try {
            Thumbnails.of(originalDrawing)
                    //缩小到30%
                    .scale(0.3)
                    //指定图片类型是支持Alpha通道
                    .imageType(BufferedImage.TYPE_INT_ARGB)
                    //将生成的缩略图写入文件
                    .toFile(new File(thumbnailUrl));
        }catch (IOException e){
            // 返回失败结果
            return "";
        }finally {
            // 移除原图本地临时文件
            if(originalDrawing.exists())    originalDrawing.delete();
        }
        // 上传到oss并获取缩略图地址
        R upload = ossFeign.uploadZip(thumbnailUrl);
        String thumbnailOssSrc = (String) upload.get("url");
        // 移除缩略图本地临时文件
        File thumbnail = new File(thumbnailUrl);
        if(thumbnail.exists())  thumbnail.delete();
        return thumbnailOssSrc;
    }

}
